package request

import (
	"compress/gzip"
	"context"
	"io"
	"io/ioutil"
	"net"
	"net/http"
	"time"
)

// request
type Request struct {
	url     string
	headers map[string]string
}

func (sr Request) addHeader(key string, value string) {
	sr.headers[key] = value
}

func (sr Request) removeHeader(key string) {
	delete(sr.headers, key)
}

func (sr Request) get() (result string, err error) {
	bytes, err := sr.getBytes()
	if err != nil {
		return "", err
	}
	return string(bytes), nil
}

func (sr Request) getBytes() (result []byte, err error) {
	client := &http.Client{
		Transport: &http.Transport{
			DialContext: func(ctx context.Context, network, addr string) (conn net.Conn, e error) {
				c, err := net.DialTimeout(network, addr, time.Second*3)
				if err != nil {
					return nil, err
				}
				return c, nil
			},
			MaxIdleConnsPerHost:   10,
			ResponseHeaderTimeout: time.Second * 2,
		},
	}
	req, err := http.NewRequest("GET", sr.url, nil)
	if err != nil {
		return nil, err
	}
	// 设置header
	for key, value := range sr.headers {
		req.Header.Add(key, value)
	}
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer func() {
		e := resp.Body.Close()
		if e != nil {
			panic(err)
		}
	}()
	var reader io.ReadCloser
	// 兼容gzip
	if resp.Header.Get("Content-Encoding") == "gzip" {
		reader, _ = gzip.NewReader(resp.Body)
	} else {
		reader = resp.Body
	}
	body, _ := ioutil.ReadAll(reader)
	return body, nil
}
